package cn.zwx.activiti.example.utils;

import cn.hutool.core.collection.CollectionUtil;
import cn.zwx.activiti.example.common.enums.ErrorEnum;
import cn.zwx.activiti.example.common.exception.BizException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.List;
import java.util.Set;

/**
 * hibernate-validator校验工具类
 *
 * 参考文档：http://docs.jboss.org/hibernate/validator/5.4/reference/en-US/html_single/
 *
 * @date 2017-03-15 10:50
 */
public class ValidatorUtils<T> {

    private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }
    private ValidatorUtils(){};
    private static final ValidatorUtils INSTANCE = new ValidatorUtils();
    public static ValidatorUtils getInstance(){
        return INSTANCE;
    }

    /**
     * 校验对象
     * @param object        待校验对象
     * @param groups        待校验的组
     * @throws BizException  校验不通过，则报RRException异常
     */
    public  void validateEntity(Object object, Class<?>... groups)
            throws BizException {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
        	ConstraintViolation<Object> constraint = (ConstraintViolation<Object>)constraintViolations.iterator().next();
            throw new BizException(ErrorEnum.PARAMS_EMPTY_ERROR.getErrorCode(),constraint.getMessage());
        }
    }

    /**
     * 校验对象
     * @param list        待校验对象
     * @throws BizException  校验不通过，则报RRException异常
     */
    public void validateList(List<T> list) throws BizException {
        if (CollectionUtil.isEmpty(list)){
            throw new BizException(ErrorEnum.PARAMS_EMPTY_ERROR.getErrorCode(),"请求参数不能为空");
        }
        for (Object o : list) {
            validateEntity(o);
        }
    }


}
